package kstech.com.wifitest;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.util.Date;

import kstech.com.wifitest.utils.DateUtil;

public class WifiReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        // TODO Auto-generated method stub
        if(intent.getAction().equals(WifiManager.RSSI_CHANGED_ACTION)){
            write("wifi signal strength changed");
            //signal strength changed
        } else if(intent.getAction().equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)){//wifi连接上与否
            System.out.println("网络状态改变");
            NetworkInfo info = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
            if(info.getState().equals(NetworkInfo.State.DISCONNECTED)){
                System.out.println("wifi网络连接断开");
                write("wifi  DISCONNECTED");
            } else if(info.getState().equals(NetworkInfo.State.CONNECTED)){

                WifiManager wifiManager = (WifiManager)context.getSystemService(Context.WIFI_SERVICE);
                WifiInfo wifiInfo = wifiManager.getConnectionInfo();

                //获取当前wifi名称
                System.out.println("连接到网络 " + wifiInfo.getSSID());
                write(" wifi CONNECTED " + wifiInfo.getSSID());
            }

        } else if(intent.getAction().equals(WifiManager.WIFI_STATE_CHANGED_ACTION)){//wifi打开与否
            int wifistate = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, WifiManager.WIFI_STATE_DISABLED);

            if(wifistate == WifiManager.WIFI_STATE_DISABLED){
                System.out.println("系统关闭wifi");
                write("  WIFI_STATE_DISABLED");
            }
            else if(wifistate == WifiManager.WIFI_STATE_ENABLED){
                System.out.println("系统开启wifi");
                write("  WIFI_STATE_ENABLED");
            }
        }
    }

    public void write(String str){
        try {
            //将crash log写入文件
            FileOutputStream fileOutputStream = new FileOutputStream("/storage/sdcard1/wifi_log.txt", true);
            PrintStream printStream = new PrintStream(fileOutputStream);
            printStream.println(DateUtil.getDateTimeFormat(new Date())+"---------------------------------------------");
            printStream.println(DateUtil.getDateTimeFormat(new Date())+"WIFI:  "+str);
            printStream.flush();
            printStream.close();
            fileOutputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
